package com.example.myapplication11;

import android.app.ActivityManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyService extends Service {
    public boolean f = true;
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    public void onCreate()
    {
        super.onCreate();
        f = true;
        Log.d("MyService", "onCreate executed");
        new Thread(){
            @Override
            public void run() {
                super.run();
                while(f){
                    try {
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //一直运行
                    boolean isRunningForeground = isRunningForeground();

                    if(isRunningForeground){
                        Log.i("Service","-----start Login activity-----");
                    }else {
                        Log.i("Service","-----start other activity-----");
                    }
                }
            }
        }.start();
    }
    public  int onStartCommand(Intent intent,int flags,int startId){
        Log.i("Service","-----service onStartCommand...");

        return super.onStartCommand(intent, flags, startId);
    }
    public void onDestroy(){

        f = false;
        super.onDestroy();
        Log.d("MyService", "onDestroy executed");
    }
    public boolean isRunningForeground() {
        ActivityManager activityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity=activityManager.getRunningTasks(1).get(0).topActivity.getClassName();
        Log.d("TAG", runningActivity);
        if(runningActivity.indexOf("Login")==-1) {
            return false ;
        }
        return true ;
    }
}